<template>
    <div>
        <el-page-header @back="goBack" class="detail-page-header">
            <template #content>
                    <!-- 显示项目名称 -->
                    <span class="text-large font-600 mr-3"> {{ '编辑纪念馆' }} </span>
            </template>
            <!-- 如果需要，可以在 PageHeader 右侧添加额外内容或操作按钮 -->
        </el-page-header>
        <el-divider />
        <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules" class="form-main">
            <el-form-item label="逝者姓名" prop="name">
                <el-input v-model="formData.name" clearable placeholder="请输入逝者姓名" class="w-[280px]"/>
            </el-form-item>

            <el-form-item label="逝者出生日期" prop="birth_date">
                <!-- <el-date-picker v-model="formData.birth_date" type="date" placeholder="请选择逝者出生日期" /> -->
                <el-input v-model="formData.birth_date" clearable placeholder="请输入逝者出生日期" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="逝者去世日期" prop="death_date">
                <!-- <el-date-picker v-model="formData.death_date" type="date" placeholder="请选择逝者去世日期" /> -->
                <el-input v-model="formData.death_date" clearable placeholder="请输入逝者去世日期" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="逝者照片" prop="avatar">
                <!-- <material-picker v-model="formData.avatar" :limit="1" /> -->
                <div style="width: 150px;height: 150px;">
                    <el-upload
                        class="avatar-uploader"
                        :action="upLoadUrl"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </div>
                
            </el-form-item>

            <el-form-item label="情感关系" prop="relationship">
                <template #default>
                    <div class="w-[280px]">
                        <el-select v-model="formData.relationship" clearable placeholder="请选择情感关系" style="width: 100%;">
                            <el-option v-for="item in relationshipList" :key="item.id" :label="item.title" :value="item.id" />
                        </el-select>
                    </div>
                </template>
                
            </el-form-item>
            <el-form-item label="宗教" prop="religion">
                <el-input v-model="formData.religion" clearable placeholder="请输入宗教" class="w-[280px]"/>
                <!-- <el-select v-model="formData.religion" clearable placeholder="请选择宗教">
                    <el-option v-for="item in religionList" :key="item.value" :label="item.name" :value="item.value" />
                </el-select> -->
            </el-form-item>
            <el-form-item label="国籍" prop="nationality">
                <el-input v-model="formData.nationality" clearable placeholder="请输入国籍" class="w-[280px]"/>
                <!-- <el-select v-model="formData.nationality" clearable placeholder="请选择国籍">
                    <el-option v-for="item in nationalityList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select> -->
            </el-form-item>
            <el-form-item label="祖籍" prop="ancestral">
                <el-input v-model="formData.ancestral" clearable placeholder="请输入祖籍" class="w-[280px]"/>
                <!-- <el-select v-model="formData.ancestral" clearable placeholder="请选择祖籍">
                    <el-option v-for="item in ancestralList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select> -->
            </el-form-item>
            <el-form-item label="职业" prop="career">
                <el-input v-model="formData.career" clearable placeholder="请输入职业" class="w-[280px]"/>
                <!-- <el-select v-model="formData.career" clearable placeholder="请选择职业">
                    <el-option v-for="item in careerList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select> -->
            </el-form-item>
            <el-form-item label="纪念馆别名" prop="alias" v-if="detailInfo.is_double == 0">
                <el-input v-model="formData.alias" clearable placeholder="请输入纪念馆别名" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="墓碑祭词" prop="sacrificial_word"  v-if="detailInfo.is_double == 0">
                <el-input v-model="formData.sacrificial_word" type="textarea" placeholder="请输入墓碑祭词" :rows="8" class="w-[280px]"/>
            </el-form-item>
            <el-divider />
            <el-form-item  v-if="detailInfo.is_double == 0">
                <el-button type="primary" @click="handleSubmit">保存</el-button>
            </el-form-item>
        </el-form>
        <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules" class="form-main" v-if="detailInfo.is_double == 1">
            <el-form-item label="逝者姓名" prop="name2">
                <el-input v-model="formData.name2" clearable placeholder="请输入逝者姓名" class="w-[280px]"/>
            </el-form-item>

            <el-form-item label="逝者出生日期" prop="birth_date2">
                <el-input v-model="formData.birth_date2" clearable placeholder="请输入逝者出生日期" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="逝者去世日期" prop="death_date2">
                <el-input v-model="formData.death_date2" clearable placeholder="请输入逝者去世日期" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="逝者照片" prop="avatar2">
                <!-- <material-picker v-model="formData.avatar2" :limit="1" /> -->

                <div style="width: 150px;height: 150px;">
                    <el-upload
                        class="avatar-uploader"
                        :action="upLoadUrl"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess2"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="formData.avatar2" :src="formData.avatar2" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </div>
            </el-form-item>

            <el-form-item label="情感关系" prop="relationship2">
                <template #default>
                    <div class="w-[280px]">
                        <el-select v-model="formData.relationship2" clearable placeholder="请选择情感关系" style="width: 100%;">
                            <el-option v-for="item in relationshipList" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </div>
                </template>
            </el-form-item>
            <el-form-item label="宗教" prop="religion2">
                <el-input v-model="formData.religion2" clearable placeholder="请输入宗教" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="国籍" prop="nationality2">
                <el-input v-model="formData.nationality2" clearable placeholder="请输入国籍" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="祖籍" prop="ancestral2">
                <el-input v-model="formData.ancestral2" clearable placeholder="请输入祖籍" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="职业" prop="career2">
                <el-input v-model="formData.career2" clearable placeholder="请输入职业" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="纪念馆别名" prop="alias" v-if="detailInfo.is_double == 1">
                <el-input v-model="formData.alias" clearable placeholder="请输入纪念馆别名" class="w-[280px]"/>
            </el-form-item>
            <el-form-item label="墓碑祭词" prop="sacrificial_word"  v-if="detailInfo.is_double == 1">
                <el-input v-model="formData.sacrificial_word" type="textarea" placeholder="请输入墓碑祭词" :rows="8" class="w-[280px]"/>
            </el-form-item>
            <el-divider />
            <el-form-item>
                <el-button type="primary" @click="handleSubmit">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script lang="ts" setup>
    import { reactive, ref, toRaw, shallowRef, defineEmits, onMounted, defineProps } from 'vue'
    import type { FormInstance, UploadProps } from 'element-plus'
    import { useRouter } from 'vue-router'
    import useUserStore from '@/stores/modules/user'
    import { apiMyMuEdit, apiMyMuDetail, apiMyMuRelation } from '@/api/graveyard'
    import { ElMessage } from 'element-plus'

    const userStore = useUserStore()
    const router = useRouter()
    const formRef = ref<FormInstance>()
    const props = defineProps({
        memorialId: {
            type: [Number, String],
            default: ''
        }
    })

    interface formDataObj {
        name: string,
        birth_date: string,
        death_date: string,
        avatar: string,
        relationship: string,
        religion: string,
        nationality: string,
        ancestral: string,
        career: string,
        alias: string,

        name2?: string,
        birth_date2?: string,
        death_date2?: string,
        avatar2?: string,
        relationship2?: string,
        religion2?: string,
        nationality2?: string,
        ancestral2?: string,
        career2?: string,
        alias2?: string
        sacrificial_word?: string
    }

    const formData = reactive({
        name: '',
        birth_date: '',
        death_date: '',
        avatar: '',
        relationship: '',
        religion: '',
        nationality: '',
        ancestral: '',
        career: '',
        alias: '',
        sacrificial_word: '',
    })

    const formData2 = reactive({
        name2: '',
        birth_date2: '',
        death_date2: '',
        avatar2: '',
        relationship2: '',
        religion2: '',
        nationality2: '',
        ancestral2: '',
        career2: '',
        alias2: ''
    })
    // 情感关系列表
    const relationshipList = ref<any[]>([])
    // 宗教列表
    const religionList = ref<any[]>([])
    // 祖籍列表
    const ancestralList = ref<any[]>([])
    // 国籍列表
    const nationalityList = ref<any[]>([])
    // 职业列表
    const careerList = ref<any[]>([])
    // 当前选中的tab
    const activeTab = ref('1')

    // 提交按钮
    const handleSubmit = async () => {
        await formRef.value?.validate()
        let data = { ...formData }
        if(activeTab.value == '2') {
            data = {...formData}
        }
        console.log('data==========================',toRaw(data))
        let params = {
            type: detailInfo.value.type, 
            user_id: detailInfo.value.user_id, 
            is_double: detailInfo.value.is_double,
        }
        await apiMyMuEdit({...data, ...params}) 
        goBack()
        // popupRef.value?.close()
        // emit('success')
    }

    // 上传图片
    const upLoadUrl = import.meta.env.VITE_APP_BASE_URL + '/api/upload/image'
    const imageUrl = ref('')
    const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
    ) => {
        formData.avatar = URL.createObjectURL(uploadFile.raw!)
    }

    const handleAvatarSuccess2: UploadProps['onSuccess'] = (
    response,
    uploadFile
    ) => {
        formData.avatar2 = URL.createObjectURL(uploadFile.raw!)
    }

    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif') {
        ElMessage.error('Avatar picture must be JPG、PNG、GIF format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
    }
    // 获取情感关系
    const getRelationshipList = async () => {
        const data = await apiMyMuRelation({page_no: 1, page_size: 9999})
        relationshipList.value = data
    }

    const detailInfo = ref<any>({})
    const getMemorialDetail = async () => {
        const res = await apiMyMuDetail({id: props.memorialId})
        console.log(res)
        detailInfo.value = res
        if(res.relationship && res.relationship != 0) {
            detailInfo.value.relationship = res.relationship
        }else{
            detailInfo.value.relationship = ''
        }
        Object.assign(formData, detailInfo.value)
    }

    const emit = defineEmits<{
        (e: 'back-to-list', from: string): void;
    }>();
	const goBack = () => {
		console.log('返回上一页...');
		// 实现返回逻辑, 比如使用 vue-router 的 router.back()
		// alert('返回上一页 (模拟)');
		emit('back-to-list', 'memorialEdit')
	};
    onMounted(() => {
        getMemorialDetail()
        getRelationshipList()
    })
</script>
<style scoped>
    .avatar-uploader{
        border: 1px dashed #cdd0d6;
        border-radius: 6px;
        overflow: hidden;
        width: 100px;
        height: 100px;
        box-sizing: border-box;
    }
    .avatar-uploader .avatar {
        width: 100px;
        height: 100px;
        display: block;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        text-align: center;
    }
</style>